package com.weidong.mybbs.config;

import com.weidong.mybbs.entity.SysUser;
import com.weidong.mybbs.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService userService;

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("执行授权逻辑:doGetAuthorizationInfo()");
        //给资源进行授权

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加资源授权字符串
        log.info("添加资源授权字符串");
        info.addStringPermission("user:add");
        return null;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("执行认证逻辑:doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        log.info("当前登录人:"+token.getUsername().trim());
        //查询用户数据
        SysUser byName = userService.findByName(token.getUsername().trim());
        //判断用户名和密码
        if (byName==null){
            //用户名不存在
            return null;
        }
        //判断密码
        return new SimpleAuthenticationInfo(byName,byName.getPassword(),"");
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo()
    {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
